﻿(function($){
    $.isIE6 = function(){
        return ($.browser.msie && $.browser.version == "6.0" && !$.support.style);
    };
    
    //提供元素a相对于元素fixedEl的位置计算，同时检测边界
    $.boundOffset = function(el, fixedEl, options){
        var settings = {
            offset: { x:0, y:0 },
            container: window,
            moreOffset: false
        };
        var opts = $.extend(settings, options);
        var offset = fixedEl.offset(),
            width = fixedEl.outerWidth(),
            elWidth = el.outerWidth(),
            container = $(opts.container),
            w = container.width(),
            sl = container.scrollLeft();
        
        var cls = ['pos-left', 'pos-right'];
        $.each(cls, function(index, value){
            el.removeClass(value);
        });
        if(offset.left + width + elWidth > w + sl){
            offset.left -= elWidth + opts.offset.x;
            el.addClass(cls[0]);
        }else{
            offset.left += width + opts.offset.x;
            el.addClass(cls[1]);
        }
        if(opts.moreOffset){
            var height = fixedEl.outerHeight(),
                h = container.height(),
                st = container.scrollTop(),
                elHeight = el.outerHeight();
            if(offset.top + elHeight > h + st){
                offset.top = h + st - elHeight - opts.offset.y;
            }else{
                offset.top -= opts.offset.y;
            }
        }
        el.css(offset);
    };

    /*:hover for ie6*/
    $.fn.hoverForIE6 = function(cls){
        if($.isIE6()){
            cls = cls || 'hover';
            return this.each(function(){
                var $this = $(this);
                $this.hover(function(){
                   $this.addClass(cls);
                }, function(){
                   $this.removeClass(cls);
                });
            });
        }
        return this;
    };

    $.fn.floatMenu = function(options){
         var settings = {
             delay: 500,
             duration: 700,
             vertical: 'bottom',
             horizon: 'right',
             relativeTo: 'body',
             fx: true,
             offset: 0,
             limit: 0
         };

         var opts = $.extend(settings, options);

         var relativeEl = $(opts.relativeTo),
             isIE6 = $.isIE6(),
             setPos = function(el){
                 if(opts.relativeTo == 'body') el.css(opts.horizon, 0);
                 else el.css('left', (opts.horizon == 'right') ? relativeEl.offset().left + relativeEl.width() - el.outerWidth() : relativeEl.offset().left);
             };

         return this.each(function(){
             var $this = $(this),
                 initTop = $this.offset().top,
                 h = $this.outerHeight(),
                 rh = relativeEl.height(),
                 rt = relativeEl.offset().top,
                 scrolling = false;

             var getTop = function(withoutFx){
                 var wh = $(window).height(),
                     st = $(window).scrollTop(),
                     top;

                 if(opts.vertical == 'top'){
                     top = (st + opts.offset <= initTop) ? initTop : st + opts.offset;
                 }else if(opts.vertical == 'bottom'){
                     top = (st + wh - (opts.offset + h) <= initTop) ? initTop : st + wh - (h + opts.offset);
                 }
                 if(opts.relativeEl != 'body') top = Math.max(rt, Math.min(rt + rh - h, top));
                 return top;
             };

             var aniTimer;
             var animate = function(){
                 scrolling = false;
                 var top = getTop();
                 if(top < opts.limit){
                     $this.hide();
                     return;
                 }else if(!(!opts.fx && isIE6)) $this.show();
                 if (opts.fx) $this.animate({top: top}, {duration:opts.duration, queue:false});
                 else if (isIE6){
                     aniTimer = setTimeout(function(){
                         if(scrolling) clearTimeout(aniTimer);
                         $this.css('top', top).fadeIn();
                     }, opts.delay);
                 };
             };

             setPos($this.css({
                 'position': (opts.fx || isIE6) ? 'absolute' : 'fixed',
                 'z-index': 9999
             }));
             animate();

             if($.browser.msie){
                 var sTimer, rTimer;
                 $(window).bind('scroll', function(){
                     clearTimeout(sTimer);
                     sTimer = setTimeout(function(){ animate(); }, 100);
                     if(!opts.fx && !scrolling){
                         $this.hide();
                         scrolling = true;
                     }
                 }).bind('resize', function(){
                     clearTimeout(rTimer);
                     rTimer = setTimeout(function(){ setPos($this); animate(); }, 100);
                 });
             }else{
                 $(window).bind('scroll', function(){
                     animate();
                 }).bind('resize', function(){
                     setPos($this);
                     animate();
                 });
             }
         });
     };

    /*dropmenu*/
    $.fn.dropMenu = function(settings){
        var options = {
            delay: 200,
            offset: { x: 0,y: 20 },
            shim: false,
            trigger: 'hover',
            menu: null
        };
        var opts = $.extend(true, {}, options, settings);

        return this.each(function(){
            var timer,
                resizer = 1,
                $this = $(this),
                _showing = false,
                _pos = {};

            var menu = opts.menu || ($this.attr('dropmenu') ? $('#'+$(this).attr('dropmenu')) : null);
            if(!menu) return false;
            menu.css({
                position: 'absolute',
                display: 'none'
            });

            if(opts.shim){
                var shim = menu.shim().next('iframe.shim').hide();
            }

            setPos();
            $(window).load(setPos).resize(function(){
                if(resizer) clearTimeout(resizer);
                resizer = setTimeout(function(){
                    setPos();
                    resizer = null;
                }, 500);
            });

            var clickBound = function(){
                hide();
                $(document).unbind('click', clickBound);
            };

            if(opts.trigger == 'hover'){
                $this.add(menu).hover(function(){
                    if(timer) clearTimeout(timer);
                    if(!_showing) show();
                }, function(){
                    timer = setTimeout(function(){
                        hide();
                    }, opts.delay);
                });
            }else{
                $this.click(function(){
                    if(!_showing) show();
                    setTimeout(function(){
                        $(document).bind('click', clickBound);
                    }, 0);
                });
            }

            function show(){
                 menu.show();
                _showing = true;
                if(shim) shim.show();
            }

            function hide(){
                menu.hide();
                _showing = false;
                if(shim) shim.hide();
            }

            function setPos(){
                var pos = $this.position();
                _pos = {
                     left: opts.offset.x + pos.left,
                     top: opts.offset.y + pos.top
                };
                menu.css(_pos);
                if(shim) shim.css(_pos);
            }
        });
    };
    
    /*popup tips*/
    $.fn.popup = function(options){
        var setting = {
            delay: 600,
            effect: true,
            duration: 300,
            content: 'title',
            offset:{
                x: 10
            }
        };
        var opts = $.extend(setting, options),
            popup = $('.x-popup').length ? $('.x-popup').eq(0) : $('<div class="x-popup popup-box"><div class="bl"><div class="br"><div class="bd"></div><i class="arr"></i></div></div><div class="bt"><div class="bt-l"><div class="bt-r"><div class="bt-b"></div></div></div></div></div>')
                    .appendTo('body'),
            pContent = popup.find('.bd'),
            showing = false,
            _show = function(el, content){
                if(showing) return;
                pContent.html(content);
                $.boundOffset(popup, el, { offset: opts.offset });
                if(opts.effect) popup.fadeIn(opts.duration);
                else popup.show();
                showing = true;
            },
            _hide = function(){
                showing = false;
                if(opts.effect) popup.fadeOut(opts.duration);
                else popup.hide();
            };
        return this.each(function(index){
            var $this = $(this),
                content, timer;

            if(opts.content == 'title'){
                content = $this.attr('title');
                $this.removeAttr('title');
            }else{
                content = $(opts.content).eq(index).html();
            }
            $this.hover(function(){
                timer = setTimeout(function(){
                    _show($this, content);
                }, opts.delay);
            }, function(){
                clearTimeout(timer);
                _hide();
            });
        });
    };
    
    $.fn.stickPopup = function(options){
        var setting = {
            content: '',
            offset:{
                x: 10
            },
            width: null,
            once: true,
            cookie: null,
            onClose: function(){}
        };
        var opts = $.extend(setting, options);
        return this.each(function(index){
            var $this = $(this),
                content, timer;
                
            var cookie = opts.cookie || (this.id ? 'tip_'+this.id : null);
            if(cookie && $.cookie(cookie)) return;
            
            var popup = $('<div class="popup-box"><div class="bl"><div class="br"><div class="bd"></div><i class="arr"></i><a class="btn-close" href="#"><i></i></a></div></div><div class="bt"><div class="bt-l"><div class="bt-r"><div class="bt-b"></div></div></div></div></div>')
                        .appendTo('body'),
                pContent = popup.find('.bd');
            
            $this.data('popup', popup);
            if(!isNaN(opts.width) && opts.width > 0) popup.css('width', opts.width);
            if(!opts.content){
                content = $this.attr('title');
                $this.removeAttr('title');
            }else if(typeof opts.content == 'string'){
                content = opts.content;
            }else if(opts.content instanceof $){
                content = $(opts.content).eq(index).html();
            }
            
            $.boundOffset(popup, $this, { offset: opts.offset });
            pContent.html(content);
            var that = this;
            popup.find('.btn-close').click(function(){
                popup.hide();
                if($.isFunction(opts.onClose)) opts.onClose.call(that);
                if(opts.once && cookie) $.cookie(cookie, 1, {expires: 9999});
                return false;
            });
            if(!opts.once || (cookie && !$.cookie(cookie))) popup.show();
        });
    };

    /*event clickoutside*/
    $.fn.clickOutside = function(callback){
        return this.each(function(){
            var that = this;
            var bindClickoutSide = function(e){
                var tgt = e.target,
                    found = false;
                while(tgt.parentNode != null){
                    if(tgt == that) {
                         found = true;
                         break;
                    }
                    tgt = tgt.parentNode;
                }
                if(found) return;
                callback.call(this);
                $(document).unbind('click', bindClickoutSide);
            };
            $(document).bind('click', bindClickoutSide);
        });
    };

    /*iframe shim*/
    $.fn.shim = function(){
        if ($.browser.msie){
			this.each(function(){
			    var element = $(this);
			    element.css({
			        'display': 'block',
			        'visibility': 'hidden'
			    });
			    var outWidth = element.outerWidth(),
			        outHeight = element.outerHeight();
			    element.css({
			        'display': 'none',
			        'visibility': 'visible'
			    });

				var pos = element.position(),
					html = '<iframe class="shim" frameborder="0" style="' +
						'display: block;'+
						'position: absolute;' +
						'top:' + pos.top + 'px;' +
						'left:' + pos.left + 'px;' +
						'width:' + outWidth + 'px;' +
						'height:' + outHeight + 'px;' +
						'z-index:' + (element.css('z-index') ? element.css('z-index')-1 : 0) + ';' +
						'"/>';

				element.after(html);
			});
        }

		return this;
	};

	$.fn.unshim = function(){
		if ($.browser.msie){
			this.each(function(){
				$(this).next("iframe.shim").remove();
			});
		}

		return this;
	};



	/*图片预览*/
	$.fn.imgPreview = function(options){
	    var setting = {
	        delay: 1000,
	        attr: 'b_src',
	        smallSize: 180,
	        largeSize: 325
	    };

	    var opts = $.extend({}, setting, options);

	    var markup = $('<div id="gimg-preview" ><div class="loading">loading....</div></div>').hide().appendTo(document.body),
            timer, delayTimer;

        return this.each(function(){
            var $this = $(this),
                img = $this.find('img');
            if(!img || !img.attr(opts.attr) || img.attr(opts.attr).indexOf('lack_pic') >= 0) return;

            $this.mouseenter(function(){
                delayTimer = setTimeout(function(){
                    attachImg(img);
                    $.isFunction(opts.onShow) && opts.onShow.call($this, markup);
                    markup.show();
                    $.boundOffset(markup, $this, { moreOffset:true, offset:{x:10, y:5}});
                }, opts.delay);
            }).mouseleave(function(){
                clearTimeout(timer);
                clearTimeout(delayTimer);
                markup.hide();
            });
        });

        function attachImg(img){
            var imgSrc = img.attr(opts.attr) || false;
            if(!imgSrc) return;
            markup.empty().html('<div class="loading">loading....</div>');
            var img = $('<img src="'+imgSrc+'"/>').load(function(){
                var $el = $(this).parent(),
                    that = this;
                timer = setTimeout(function(){
                    $el.css('display', '');
                    if(that.width >= that.height) that.width = opts.largeSize;
                    else that.height = opts.largeSize;
                    markup.find('.loading').hide();
                }, 300);
            });
            return $('<div class="gpreview" />').append(img).appendTo(markup).hide();
        }
	};

	$.fn.imgResize = function(w, h){
	    h = h || w;
	    return this.each(function(){
	        if(this.tagName != 'IMG') return;
	        var $this = $(this),
	            pic = this;
	        pic.removeAttribute('width');
	        pic.removeAttribute('height');
	        if(pic.width > w || pic.height > h){
                var width = pic.width, height = pic.height, scale = pic.width / pic.height, ratio = Math.min(1, w / width);
                for(var i = 2; i--; ){
                    width *= ratio;
                    height = width / scale;
                    ratio = Math.min(1, h / height);
                }
    	        pic.width = width;
    	        pic.height = height;
	        }
	        if(pic.height < h) $this.css('margin-top', (h-pic.height)/2);
	    });
	};


    $.fn.imgZoom = function(options){
        var setting = {
           width: 400,
           height: 400,
           jqSrc: 'jqsrc',
           requireSize: 550,
           spotSize: 200,
           viewSize: 400,
           offset: {
               left: 5,
               top: 0
           }
        };

       var opts = $.extend(setting, options),
           $this = $(this),
           offset = $this.offset(),
           cancel = false,
           imgZoom, imgSpot, zImg,
           imgWidth, imgHeight,
           offsetWidth, offsetHeight,
           marginLeft, marginTop;

       var limit = function(num, min, max){
           return Math.max(min, Math.min(num, max));
       };

       $this.hover(function(){
           var $img = $this.find('img');
           if($img.attr('src').indexOf('lack') >= 0) return (cancel = true);
           else cancel = false;
           marginLeft = ($this.width() - $img.width())/2;
           marginTop = ($this.height() - $img.height())/2;
           imgWidth = $img.get(0).width;
           imgHeight = $img.get(0).height;
           offsetWidth = imgWidth - opts.spotSize;
           offsetHeight = imgHeight - opts.spotSize;

           imgSpot = $this.find('.img-spot').length ? $this.find('.img-spot') : $('<div class="img-spot"></div>').css({
                width: opts.spotSize,
                height: opts.spotSize,
                top: 0,
                left: 0,
                display: 'none'
           }).appendTo($this);
           imgZoom = $('<div class="img-zoom"></div>').css({
               left: offset.left + $this.outerWidth() + opts.offset.left,
               top: offset.top + opts.offset.top,
               width: opts.width,
               height: opts.height
           }).insertAfter($this);
           zImg = $('<img src="'+$img.attr(opts.jqSrc)+'" />').load(function(){
               imgSpot.show();
               if(this.width < opts.width || this.height < opts.height){
                   if(this.width < this.height){
                       $(this).attr('width', opts.width);
                   }else {
                       $(this).attr('height', opts.height);
                   }
               }
           }).appendTo(imgZoom);
       }, function(){
           $this.parent().find('.img-spot, .img-zoom').remove();
       }).mousemove(function(e){
            if(cancel) return;
             var size = {
                 'left': limit(e.pageX - offset.left - opts.spotSize/2, 0, offsetWidth),
                 'top': limit(e.pageY - offset.top - opts.spotSize/2, 0, offsetHeight)
             };
             if(imgSpot) imgSpot.css({
                 'left': size.left + marginLeft,
                 'top': size.top + marginTop
             });
             if(zImg) zImg.css({
                 'left': - size.left * (zImg.get(0).width - opts.width) / offsetWidth,
                 'top': - size.top * (zImg.get(0).height - opts.height) / offsetHeight
             });
         });
         return this;
    };

	/*tabSwitcher*/
    $.fn.tabSwitcher = function(options) {
    	var settings = {
    		startIndex: 0,
    		activeCls: "cur",
    		tabCls: ".tab",
    		itemCls: ".tab-item",
    		delay: 0,
    		duration: 5000,
    		autoPlay: false,
    		trigger: "click",
    		omitLinks: false,
    		effect: false
    	};

    	var opts = $.extend({}, settings, options);
    	opts.trigger = (opts.trigger == 'hover') ? 'mouseenter' : opts.trigger;

    	this.each(function() {
    		var $this = $(this),
    		    tabs = $this.find(opts.tabCls),
    		    items = $this.find(opts.itemCls),
    		    current = -1,
    		    timer, autoRunning;

    		items.hide();
    		show(opts.startIndex);
    		if(opts.autoPlay){
    	        startPlay();
    	        $this.hover(function(){
    			    if(autoRunning) clearTimeout(autoRunning);
    		    }, function(){
    		        startPlay();
    		    });
    		}

    		tabs.each(function(index, el){
    		    if(opts.delay > 0){
    		        $(el).hover(function(){
    					timer = setTimeout(function(){
    						show(index);
    					}, opts.delay);
    				},function(){
    					if(timer) clearTimeout(timer);
    				});
    		    }else{
    		        $(el).bind(opts.trigger, function(){
        		       show(index);
        		    });
    		    }
    		});

    		function show(index){
        		if(index != current){
        			tabs.eq(current).removeClass(opts.activeCls);
        			items.eq(current).hide();
        			if(opts.effect){
        				if (opts.effect == 'slide') items.eq(index).fadeIn({queue: false, duration: 300});
        				else items.eq(index).fadeIn({queue: false, duration: 300});
        			}else{
        			    items.eq(index).show();
        			}
        			tabs.eq(index).addClass(opts.activeCls);
        			current = index;
        			if(opts.onShow) opts.onShow.apply(this, [current, tabs, items]);
        		}
        	};

        	function showNext(){
        	    var next = (current >= tabs.length -1) ? 0 : current+1;
        	    show(next);
        	};

        	function startPlay(){
        	    autoRunning = setInterval(function(){
    				showNext();
    			}, opts.duration);
        	}
    	});

    	return this;
    };

	/*滑动广告*/
	$.fn.tgSlider = function(options){
	    var settings = {
	        btnPrevCls: '.btn-prev',
	        btnNextCls: '.btn-next',
	        pageCls: '.ctl-page',
	        containerCls: '.slide-content',
	        itemCls: 'li',
	        activeCls: 'cur',
	        perItem: 5,
	        startIndex: 0,
	        autoPlay: false,
	        duration: 5000,
	        fxDuration: 600,
	        circle: true,
	        direction: 'horizon',
	        onShow: function(){ }
	    };

	    var opts = $.extend({}, settings, options);

	    var $this = $(this),
	        that = this,
	        container = $this.find(opts.containerCls),
	        items = container.find(opts.itemCls),
	        pages = $this.find(opts.pageCls),
	        btnPrev = $this.find(opts.btnPrevCls),
	        btnNext = $this.find(opts.btnNextCls);

	    if(!container || !items) return false;
	    var itemSize = (opts.direction != 'vertical') ? items.outerWidth() : items.outerHeight(),
            total = items.length,
            perItem = opts.perItem,
            current = -1,
            busy = false,
            playTimer;
        
        if(total <= perItem){
            btnPrev && btnPrev.addClass('disabled');
            btnNext && btnNext.addClass('disabled');
            return;
        }
        
        container.css((opts.direction != 'vertical') ? 'width' : 'height', itemSize * total);

        this.show = function(index){
            if(index == current || busy) return;
            index = Math.max(0, Math.min(index, items.length - 1));
            if(pages.length) pages.eq(current).removeClass(opts.activeCls);
            busy = true;
            var fxOpts = {};
            fxOpts[(opts.direction != 'vertical') ? 'left' : 'top'] = - index * itemSize;
            container.animate(fxOpts, opts.fxDuration, function(){
                busy = false;
            });
            current = index;
            if(pages.length) pages.eq(current).addClass(opts.activeCls);
            if(!opts.circle){
                if(current == 0){
                    btnPrev.addClass('disabled');
                }else if (current >= total - perItem || total < perItem){
                    btnNext.addClass('disabled');
                }else{
                    btnPrev.add(btnNext).removeClass('disabled');
                }
            }

            opts.onShow.apply(this, [current, items]);
        };

        if(btnPrev.length) btnPrev.click(showPrev);
        if(btnNext.length) btnNext.click(showNext);
        if(pages.length) pages.each(function(index){
            $(this).click(function(){
                that.show(index);
            });
        });

        this.show(opts.startIndex);
        if(opts.autoPlay) {
            autoPlay();
            $this.hover(function(){
                if(playTimer) clearTimeout(playTimer);
            }, function(){
                autoPlay();
            });
        }

        function showNext(){
            if(current + perItem < total) that.show(current+1);
            else if(opts.circle) that.show(0);
            else return;
        }

        function showPrev(){
            if(current > 0) that.show(current-1);
            else if(opts.circle && total >= perItem) that.show(total - perItem);
            else return;
        }

        function autoPlay(){
            playTimer = setInterval(function(){
                showNext();
            }, opts.duration);
        }

        return this;
	};
	
	$.fn.marquee = function(options){
	    var setting = {
	        delay: 2000,
	        duration: 500,
	        itemCls: 'li'
	    };
	    
	    var opts = $.extend(setting, options);
	    return this.each(function(){
	        var $this = $(this),
	            timer;
	            	        
	        $this.hover(function(){
	            clearInterval(timer);
	        }, function(){
	            timer = setInterval(function(){
	                var first = $this.find(opts.itemCls).eq(0);
	                first.animate({ marginTop: -first.outerHeight()+'px'}, opts.duration, function(){
	                    first.css('marginTop', 0).appendTo($this);
	                });
	            }, opts.delay);
	        }).trigger('mouseleave');
	    });
	};

    //倒计时
    //mode: 1.天时分秒   2.时分秒  3.时分毫秒
	$.fn.timeCountDown = function(options){
        var setting = {
           start: null,
           end: new Date(Date.UTC(2050, 0, 1)),
           now: new Date().getTime(),
           mode: 1,
           cls: {
               day: 'ct-day',
               hour: 'ct-hour',
               min: 'ct-min',
               sec: 'ct-sec',
               dsec: 'ct-dsec'
           },
           startHtml: '尚未开始',
           endHtml: '已结束',
           padding: true,
           useHtml: false
       };

       var opts = $.extend({}, setting, options),
           els = {};
        
       var htmls = [
           '<span class="'+opts.cls['day']+'"></span>天',
           '<span class="'+opts.cls['hour']+'"></span>小时',
           '<span class="'+opts.cls['min']+'"></span>分',
           '<span class="'+opts.cls['sec']+'"></span>'+(opts.mode == 3 ? '<span class="'+opts.cls['dsec']+'"></span>' : '') +'秒'
       ];
       if(opts.mode != 1) htmls.splice(0, 1);
              
       return this.each(function(){
           var $this = $(this),
               timer,
               timeLeft = Math.floor((opts.end - opts.now) / 1000);
           
           if(!opts.useHtml) $this.html(htmls.join(' '));
           for(var p in opts.cls) els[p] = $this.find('.'+opts.cls[p]) || null;
           if(opts.end && _cmpTime(opts.end, opts.now) <= 0) {
               $this.html(opts.endHtml);
               return false;
           } else if(opts.start && _cmpTime(opts.start, opts.now) > 0){
               $this.html(opts.startHtml);
               return false;
           }

           timer = setInterval(function(){
               var time = _dv(timeLeft);
               for(var p in els){
                   if(p != null) els[p].html(time[p]);
               }
               if(opts.end && timeLeft <= 0) {
                   $this.html(opts.endHtml);
                   if(opts.onEnd && $.isFunction(opts.onEnd)) opts.onEnd.call(this);
                   if(timer) clearTimeout(timer);
                   if(timer2) clearTimeout(timer2);
                   return;
               }
               timeLeft--;
           }, 1000);
           
           if(opts.mode == 3){
               var dsec = 0,
                   timer2 = setInterval(function(){
                   dsec = (++dsec) % 10;
                   els.dsec.html('.'+(9-dsec));
               }, 100);
           } 
       });

       function _dv(dur){
   		    pms = {
       			sec: 0,
       			min: 0,
       			hour: 0,
       			day: 0
   		    };

   		if(dur > 0){
   			pms.sec = _zero(dur % 60);
   			pms.min = Math.floor((dur / 60)) > 0? _zero(Math.floor((dur / 60)) % 60) : "0";
   			pms.hour = Math.floor((dur / 3600)) > 0? (opts.mode == 2 || opts.mode == 3) ? parseInt(Math.floor(dur / 3600), 10) : _zero(Math.floor((dur / 3600)) % 24) : "0";
   			if(els.day) pms.day = Math.floor((dur / 86400)) > 0? _zero(Math.floor((dur / 86400))) : "0";
       		//if(els.month) pms.month = Math.floor((dur / 2629744)) > 0? _zero(Math.floor((dur / 2629744)) % 12) : "00";
   			//if(els.year) pms.year = Math.floor((dur / 31556926)) > 0? Math.floor((dur / 31556926)) : "0";
       	    }
       		return pms;
       }

       function _zero(num){
           var n = num;
           if(opts.padding){
               n = parseInt(num, 10);
               if(n > 0 && n <= 9) n = '0' + n;
               else if(n <= 0) n = '0';
           }
           return n.toString();
       }

       function _cmpTime(t, now){
           if(!now) now = new Date().getTime();
           return (t - now);
       }

   };
   
   //tooltip
   $.fn.tooltip = function(){
       if(this.length == 0) return;
       return this.each(function() {
       	var text = $(this).attr("title");
       	$(this).attr("title", "");
       	if(text != undefined) {
       		$(this).hover(function(e){
       			var tipX = e.pageX + 12;
       			var tipY = e.pageY + 12;
       			$(this).attr("title", ""); 
       			$("body").append("<div id='tooltip'>" + text + "</div>");
       			if($.browser.msie) var tipWidth = $("#tooltip").outerWidth(true)
       			else var tipWidth = $("#tooltip").width()
       			$("#tooltip").width(tipWidth);
       			$("#tooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
       		}, function(){
       			$("#tooltip").remove();
       			$(this).attr("title", text);
       		});
       		$(this).mousemove(function(e){
       			var tipX = e.pageX + 12;
       			var tipY = e.pageY + 12;
       			var tipWidth = $("#tooltip").outerWidth(true);
       			var tipHeight = $("#tooltip").outerHeight(true);
       			if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
       			if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
       			$("#tooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
       		});
       	}
       });
   };
   
   // $(function(){
   //     $('.help-ico').tooltip();
   // })

	//文本框默认显示
	$.fn.inputDef=function(){
			var $this=$(this);
			var $parent=$this.parent();
			var $label=$("label[forinput='"+$this.attr("id")+"']");
            var str=$this.val()?$.trim($this.val()):"";
			$parent.css("position","relative");
            reset();
            function reset(){
                if(str===""){
					$label.css("color","#999").show();
				}else{
					$label.hide();
				}
            }
			$this.focusin(function(){
				reset();
			});
			$this.keydown(function(){
				$label.fadeOut();
			});
			$this.focusout(function(){
                str=$this.val()?$.trim($this.val()):"";
				if(!str){
					
					$label.fadeIn("fast",function(){
						$label.css("color","#666");	
					});
					
					$this.val("");
				}	
			});
            $label.click(function(){
                $this.focus();
            });
		};		
})(jQuery);


function ajax_page_load(query_string,page_name,page_value,div_id){
	$.ajax({
	   type: "post",
	   url: "index.php?",
	   cache: false,
	   data: query_string+"&"+page_name+"="+page_value,
	   success: function(msg){
		$('#'+div_id).html(msg);
	   }
	});
}


/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
